import React, { createContext, useState } from "react";
import classNames from "classnames";
import { TabItemProps } from "./TabItem";

export enum TabsMode {
  Horizontal = "horizontal",
  Vertical = "vertical",
}
export enum TabsSize {
  Large = "large",
  Small = "small",
}
// type TabsMode = "horizontal" | "vertical";
// type TabsSize = "small" | "large";
type SelectCallback = (selectIndex: string) => void;
export interface TabsProps {
  defaultActiveKey?: string;
  size?: TabsSize;
  className?: string;
  mode?: TabsMode;
  style?: React.CSSProperties;
  onSelect?: (selectIndex: string) => void;
  children?: React.ReactNode;
}

interface ITabsContext {
  index?: string;
  onSelect?: SelectCallback;
}
export const TabsContext = createContext<ITabsContext>({ index: "0" });

const Tabs = (props: TabsProps) => {
  const {
    defaultActiveKey,
    size,
    mode,
    onSelect,
    children,
    className,
    style,
    ...restProps
  } = props;
  const [currentActive, setActive] = useState(defaultActiveKey);
  const classes = classNames("coerger-tabs", className, {
    "tabs-vertical": mode === "vertical",
    "tabs-horizontal": mode === "horizontal",
    [`tabs-${size}`]: size,
  });

  const renderChildren = () => {
    return React.Children.map(children, (child, index) => {
      const childElement =
        child as React.FunctionComponentElement<TabItemProps>;
      const { displayName } = childElement.type;
      if (displayName === "TabItem") {
        return React.cloneElement(childElement, { index: index.toString() });
      } else {
        console.error("Waring:Tabs has a child which is not a TabItem");
      }
    });
  };

  const handleClick = (index: string) => {
    setActive(index);
    if (onSelect) {
      onSelect(index);
    }
  };
  const passedContent: ITabsContext = {
    index: currentActive ? currentActive : "0",
    onSelect: handleClick,
  };
  const renderDiv = () => {
    return React.Children.map(children, (child, i) => {
      const classPane = classNames("coerger-pane", {
        "pane-hidden": currentActive !== i.toString(),
      });
      const childElement =
        child as React.FunctionComponentElement<TabItemProps>;
      const { displayName } = childElement.type;
      if (displayName === "TabItem") {
        return (
          childElement.props.children && (
            <div className={classPane}>{childElement.props.children}</div>
          )
        );
      } else {
        console.error("Waring:Tabs has a child which is not a TabItem");
      }
    });
  };
  return (
    <>
      <TabsContext.Provider value={passedContent}>
        <ul className={classes} style={style} {...restProps}>
          {renderChildren()}
        </ul>
        {renderDiv()}
      </TabsContext.Provider>
    </>
  );
};
Tabs.defaultProps = {
  defaultActiveKey: "0",
  mode: TabsMode.Vertical,
  size: TabsSize.Small,
};
export default Tabs;
